<template>
  <div class="flex flex-wrap gap-4">
    <el-card style="font-size: 15px;font-weight: bold;margin-bottom: 10px" shadow="always"><span style="color: #535bf2">|</span>
      购物车列表页
    </el-card>
  </div>
  <div class="shopcartList" style="padding-top: 30px">
    <el-button style="margin-left: 15px;" type="primary" @click="addView">添加购物车</el-button>
    <el-button type="danger" @click="batchDel">批量删除</el-button>
    <el-table
        :data="shopcartList"
        style="width: auto"
    >
      <el-table-column type="selection" width="50" show-overflow-tooltip/>
      <el-table-column type="index" label="序号" width="150" show-overflow-tooltip/>

      <!--      prop属性的值要和后端传过来的保持一致
      -->
      <el-table-column prop="id" label="ID" width="200" show-overflow-tooltip/>
      <el-table-column prop="cartId" label="购物车ID" width="200" show-overflow-tooltip></el-table-column>

      <el-table-column prop="userId" label="用户ID" width="200" show-overflow-tooltip/>
      <el-table-column style="" label="操作" width="230">
        <template #default="scope">
          <el-button type="primary" @click="view(scope.row.id)">详情</el-button>
          <el-button  type="success" @click="editView(scope.row.id)">编辑</el-button>
          <el-button type="danger" @click="delshopcart(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination style="justify-content: center;margin-top: 10px"
                   background
                   layout="prev, pager,next"
                   :page-size=pageSize
                   :total=total
                   @current-change="toPage"
                   @prev-click="toPage"
                   @next-click="toPage"
    />
    <el-dialog v-model="dialogVisible" width="1000px" :title="shopCartQuery.id !=null ? '购物车详情' : '新增购物车'"
               draggable="true" center>
        <el-form-item v-if="shopCartQuery.id !=null" label="ID：" prop="id">
          <span class="detail">{{ shopCartQuery.id }}</span>
        </el-form-item>
        <el-form-item label="购物车ID：" prop="cartId">
          <el-input type="text" v-if="shopCartQuery.id==null" v-model="shopCartQuery.cartId"/>
          <span class="detail" v-else>{{ shopCartQuery.cartId }}</span>
        </el-form-item>
        <el-form-item  label="用户名：">
          <!--        如果是添加，下拉菜单-->
          <el-select style="width: 150px"
                     v-if="shopCartQuery.userId==null"
                     v-model="shopCartQuery.userId"
                     placeholder="请选择用户"
                     @click="loadUser"
                     clearable>
            <el-option
                v-for="item in userOptions"
                :key="item.userId"
                :label="item.userName"
                :value="item.userId"/>
          </el-select>

          <!--        否则就是详情，展示数据-->
          <span class="detail" v-else>{{ shopCartQuery.userId }}</span>
        </el-form-item>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button v-if="shopCartQuery.id==null" type="primary" @click="addShopCartSubmit">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="editDialogVisible" width="1000px" draggable="true" center>
      <!--      是一个form表单，数据绑定到 shopCartQuery-->
      <el-form ref="addRefForm" :model="editShopCartQuery" label-width="auto"  style="max-width: 800px">
        <el-form-item label="购物车ID：" prop="cartId">
          <el-input v-model="editShopCartQuery.cartId"/>
        </el-form-item>
        <el-form-item  label="用户名：">
          <el-select style="width: 150px"
                     v-model="editShopCartQuery.userId"
                     placeholder="请选择用户"
                     @click="loadUser"
                     clearable>
            <el-option
                v-for="item in userOptions"
                :key="item.userId"
                :label="item.userName"
                :value="item.userId"/>
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="editUserSubmit">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {doDelete, doGet, doPost, doPut} from "../http/httpRequest.js";
import {messageConfirm, messageTip} from "../util/util.js";
import qs from "qs";


export default {
  name: "ShopCartView",
  // 直接复制粘贴这行，后面会用到 this.reload() 表示刷新页面，当 成功执行增删改时，数据都要进行刷新，后面会用到
  inject: ['reload'],
  data() {
    return {
      // 用来存放user列表数据(绑定)，有多条数据所以使用[]
      shopcartList: [],
      // 添加用户和用户详情的弹窗，false为关闭状态，true为开启状态
      dialogVisible: false,
      editDialogVisible: false,
      editShopCartQuery: {},
      shopCartQuery: {},
      userOptions: [{}],
      // 后端传来的每页展示的条数
      pageSize: 0,
      // 总条数
      total: 0,
    }
  },
  mounted() {
    this.loadshopcartList(1);
  },
  methods: {
    toPage(current) {
      this.loadshopcartList(current)
    },
    // 查询用户列表 参数为当前页，
    loadshopcartList(current) {
      // 第一个参数为请求路径 第二个参数为请求所携带的参数，分页查询数据，携带current表示当前页数，后端通过req.getParameter("current")获取到
      doGet("/admin/shopCart", {
        // 注意
        current: current,
      }).then((resp) => {
        // 打印后端响应的数据，F12调试控制台，查看返回的数据格式
        console.log(resp)
        // this.total = resp.data.data.total
        if (resp.data.code === 200) {
          this.shopcartList = resp.data.data.list
          this.pageSize = resp.data.data.pageSize
          this.total = resp.data.data.total
        }
      })
    },
    delshopcart(id) {
      messageConfirm("是否删除该购物车？").then(() => {
        doDelete("/admin/shopCart/" + id).then((resp) => {
          if (resp.data.code === 200) {
            messageTip("删除成功!", "success")
            this.reload()
          }
        })
      })
    },
    // 方法是打开添加用户的弹窗
    addView() {
      // 添加用户确保shopCartQuery中没数据 然后在弹开
      // shopCartQuery在根据id查询用户时进行了数据绑定，添加用户时，shopCartQuery中的数据没用了，清空，
      this.shopCartQuery = {}
      this.dialogVisible = true
    },
    // 添加用户的按钮，这个方法才真正执行了添加方法
    addShopCartSubmit() {

      if (!this.shopCartQuery.cartId) {
        messageTip("cart_id 不能为空", "error");
        return;
      }
      doPost("/admin/shopCart/save", this.shopCartQuery).then((resp) => {
        if (resp.data.code === 200) {
          this.dialogVisible = false;
          messageTip("添加成功", "success");
          // 添加数据成功，需要进行页面刷新 调用该方法
          this.reload();
        } else {
          messageTip("添加失败", "error");
        }
      });
    },
    view(id) {
      doGet("/admin/shopCart/" + id).then((resp) => {
        // 不管怎样，打印查看响应的resp 看看是否成功
        console.log(resp)
        // 200 表示成功，成功就可以进行数据绑定了，让后呈现数据了
        if (resp.data.code === 200) {
          // 根据最前面变量定义，shopCartQuery表示  添加用户 或 查看用户详情 数据信息进行绑定
          this.shopCartQuery = resp.data.data
          // 表示打开弹窗 此时后端的数据已经绑定到shopCartQuery中了
          this.dialogVisible = true
        }
      })
    },
    editView(id) {
      doGet("/admin/shopCart/" + id).then((resp) => {
        console.log(resp)
        if (resp.data.code === 200) {
          this.editShopCartQuery = resp.data.data
          this.editDialogVisible = true
        }
      })
    },
    editUserSubmit() {
      //let data = qs.stringify(this.editShopCartQuery, {encode: false})
      //console.log(data)
      doPut("/admin/shopCart", this.editShopCartQuery).then((resp) => {
        console.log(resp)
        if (resp.data.code === 200) {
          this.editDialogVisible=false
          messageTip("修改成功！","success")
          this.reload()
        }
      })
    },
    loadUser() {
      doGet("/admin/user", {current: "1"}).then((resp) => {
        console.log(resp.data.data.list)
        if (resp.data.code === 200) {
          // 将后端的数据信息赋值给 userOptions,数据绑定，后续可以在下拉框中取出
          this.userOptions = resp.data.data.list
        }
      })
    }
  }
}
</script>

<style scoped>
.shopcartList {

  width: auto;
  height: auto;
  background-color: #ffffff;
}
</style>